package com.timmy.bluetooth.utils;


/**
 * 16进制相关的方�?
 * @author EX-XIAOFANQING001
 *
 */
public abstract class Hex {
	
	public static String bytesToHexString(byte[] data) {
		
		if (data == null || data.length == 0) {
			return null;
		}
		
		char[] chars = new char[data.length << 1];
		
		byte b = 0;
		int j =0;
		for (int i=0; i<data.length; i++) {
			b = data[i];
			chars[j++] =  (char) ((b & 0xf0) >> 4); 
			chars[j++] = (char) (b & 0x0f); 
		}

		StringBuffer buffer = new StringBuffer();
		for (int k=0; k<chars.length; k++) {
			buffer.append(Integer.toHexString(chars[k]));
			
			if (k % 2 != 0) {
				buffer.append(" ");
			}
		}
		return buffer.toString();
	}
	
	public static byte[] hexStringToBytes(String hexString) {
		if (hexString == null || hexString.trim().length() == 0) {
			return null;
		}
		
		byte[] bytes = new byte[hexString.length() >> 1];
		
		int j=0;
		for (int i=0; i<hexString.length(); i++) {
			char c1 = hexString.charAt(i);
			byte gw = (byte) Character.digit(c1, 16); // 高位
			
			i++;
			char c2 = hexString.charAt(i);
			byte dw = (byte) Character.digit(c2, 16);
			
			bytes[j] = (byte) ((gw << 4) | dw);
			
			j++;
		}
		
		return bytes;
	}
}
